// https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/flat
// 使用递归的方式拍平数组
// 第一种方式：reduce + concat + isArray + recursivity
const arrTemp = [1, [2, [3, [4, [5, [6]]]]]];
const flatDeep = (arr, depth = 1) => {
  return depth > 0
    ? arr.reduce(
        (account, val) =>
          account.concat(Array.isArray(val) ? flatDeep(val, depth - 1) : val),
        []
      )
    : arr.slice();
};
console.log(flatDeep(arrTemp, Infinity));
console.log(Infinity - 1);

// 第二种方式：forEach+isArray+push+recursivity
const eachFlat = (arr, depth = 1) => {
  const result = []; // 缓存递归结果
  (function flat(arr, depth) {
    arr.forEach((item) => {
      if (Array.isArray(item) && depth > 0) {
        flat(item, depth - 1);
      } else {
        result.push(item);
      }
    });
  })(arr, depth);
  return result;
};
console.log(eachFlat(arrTemp, Infinity)); // [ 1, 2, 3, 4, 5, 6 ]
console.log(eachFlat(arrTemp, 1)); // [ 1, 2, [ 3, [ 4, [Array] ] ] ]
